<?php

namespace Users\Login;

use Pinenut\User\Auth\Model;
use Users\Helper\SmartRedirect;

/**
 * Общий скелет авторизации
 *
 * @author kosh
 *        
 */
abstract class Action extends \Action {

	function privileges() {
		return '#unauthorized';
	}
	
	
	abstract function auth();
	abstract function afterLogin();
	protected $auth;
	protected $profile;
	protected function run() {

		$onlyRender = $this->response->onlyRender = (bool)$this->request->onlyRender;
		$this->response->noCache(!$onlyRender);

		if (!$onlyRender && !$this->request->isPartial) {
			$redirectUrl = $_SERVER['HTTP_REFERER'];
			if (!empty($redirectUrl)) {
				SmartRedirect::rememberRedirectPoint($redirectUrl);
			}
		}

		// аутентифицируемся
		$auth = $this->auth ();
		if ($auth instanceof Model) {
			$ref = $auth->profile->get ();
			if ($ref) {
				$profile = $ref->getEntity ();
			}
			if (! $profile) {
				throw new \Exception ( 'Profile not found' );
			}
			// аутентифицируем
			\Application::auth ()->login ( ( string ) $profile );
			$this->profile = $profile;			
			$this->afterLogin ();
		}
	}
}